from pdfminer.high_level import extract_text
from pdfminer.pdfpage import PDFPage
import fitz  # PyMuPDF
import os


def extract_text_by_page(file_path):
    text_list = []
    with open(file_path, 'rb') as file:
        for page_number, page in enumerate(PDFPage.get_pages(file), start=1):
            text = extract_text(file_path, page_numbers=[page_number - 1])
            text_list.append(text)
    return text_list


def remove_spaces_and_empty_lines(text):
    # 去除所有空格
    text_no_spaces = text.replace(" ", "")
    text_no_spaces = text_no_spaces.replace("：", ":")
    text_no_spaces = text_no_spaces.replace("）", ")")
    text_no_spaces = text_no_spaces.replace("（", "(")
    text_no_spaces = text_no_spaces.replace("¥", "￥")
    # 去除所有空行
    lines = text_no_spaces.splitlines()
    non_empty_lines = [line for line in lines if line.strip() != ""]
    cleaned_text = "\n".join(non_empty_lines)
    return cleaned_text


def convert_pdf_to_images(pdf_path, output_folder, zoom=2):
    # 创建输出文件夹
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    file_name = os.path.basename(pdf_path)

    # 打开PDF文件
    pdf_document = fitz.open(pdf_path)

    image_paths = []

    # 遍历PDF的每一页
    for page_number in range(len(pdf_document)):
        page = pdf_document.load_page(page_number)

        # 设置缩放因子，缩放因子越大，图片越清晰
        matrix = fitz.Matrix(zoom, zoom)
        pix = page.get_pixmap(matrix=matrix)

        # 保存每一页为图片
        image_filename = f"{file_name}_page_{page_number + 1}.png"
        image_path = os.path.join(output_folder, image_filename)
        pix.save(image_path)
        image_paths.append(image_path)

    return image_paths
